--
-- Author: shunguo.chen
-- Date: 2017-06-20 12:12:11
--
-- IconRender 对 Res.BaseIcon 的解析

local ClassRef = app.mvc.createRenderClass(...)
local newFloatTipsView = require("app.newFloatTips.newFloatTipsView")

-- data = Item/Equip/Mount/Fame/Tool/Daibi/MountSoul
function ClassRef.createWithData(data, node)
	local sprite = ClassRef.extend(node or cc.CSLoader:createNode(Res.BaseIcon))
	if node == nil then
		ccui.Helper:doLayout(sprite)
	end
	sprite:init(data)
	return sprite
end


function ClassRef.create(node, isMultipleLayerNode)
	if not node then
		node = display.createMultipleLayerRenderWithCsbPath(Res.BaseIcon, isMultipleLayerNode)
	end
	local sprite = ClassRef.extend(node)
	sprite:init()
	return sprite
end

function ClassRef:init(data)
	self.super.init(self, data)

	self._tipEnable = false
	self._isTouchTip = false
	self._extraTipsContent = nil

    self._comparedTipEnable = false
	self._defaultShowNumLimit = 2
	-- 兼容 多层节点优化
	self._panel = self:getChildByName('Panel')
	if not self._panel then
		self._panel = self
	else
		self:setContentSize(self._panel:getContentSize())
	end

	self:setSelected(false)
	display.uiAddClick(self._panel, function(sender, eventType)
			if self._isTouchTip then
				self:setSelected(false)
			else
				self:setSelected(not self:isSelected())
				executeFunc(self._onClick, self)
				self:dispatchCellEvent("click", self)
				if self:isSelected() then
					self:showTip()
				end
			end
		end)

	self:refresh()
end

function ClassRef:setNewScale(len)
    self:setAnchorPoint(cc.p(0.5, 0.5))
	local size = self:getContentSize()
	local scale = len / size.height
	self:setScale(scale)
end

function ClassRef:refresh()
	self:setIconType(nil)
	if self._data then
        self:setLevelVisible(true)
        self:setPanelNumVisible(true)

		local type = self._data.itemBagType
		local data = self._data

		self:setLevel()
		self:setEquiped( false )
		self:setChooseToCompose(false)
		self:hideStar()
		if type == Enums.ItemBagType.daibi then
			self:setNewTipVisibla(data.isNew or false)
			self:setIcon(data:getIcon())
			self:setNum(data:getAmount())
			self:setIconKuang(data:getIconBg())
			-- 如果有level 就显示level
			local level = data:getLevel()
			if level then
				self:setLevelEx(tonumber(level))
			end
		elseif type == Enums.ItemBagType.mount then
			self:setNewTipVisibla(data.isNew)
			self:setNum()
			self:setIcon(data:getIcon())
			self:setIconKuang(data:getIconBg())
		elseif type == Enums.ItemBagType.partner then --随从
			self:setNewTipVisibla(data.isNew)
			self:setNum()
			self:setIcon(data:getTipsIcon())
			self:setIconKuang(data:getIconBg())
			self:setStar(data:getStar())
		elseif type == Enums.ItemBagType.fashion then --时装
			self:setNewTipVisibla(data.isNew)
			self:setNum(1)
			self:setIcon(data:getIcon())
			self:setIconKuang(data:getIconBg())
		elseif type == Enums.ItemBagType.equip or type == Enums.ItemBagType.item then
			self:setNewTipVisibla(data.isNew)
			self:setIcon(data:getIcon())
			self:setIconKuang(data:getIconBg())
			self:setNum(data:getAmount())
			if type == Enums.ItemBagType.equip then
				self:setEquiped( UD:isEquiped( data ) )
            else
    			if self._data:getItemType() == Enums.ItemType.crystal then
    				--如果是水晶 设置显示等级
    				local rockInfo = GD:queryRockById(self._data:getId())
    				if rockInfo then
    					self:setLevelEx(tonumber(rockInfo.leve))
    				end
    			end
			end
		elseif type == Enums.ItemBagType.partnerEquip then
			self:setNewTipVisibla(false)
			self:setIcon(data:getIcon())
			self:setIconKuang(data:getIconBg())
			self:setNumBgVisible( false )
			-- self:setLevelEx(data:getStrengthenLevel())
		elseif type == Enums.ItemBagType.jewel then -- 宝石不显示数量？？？
			self:setNewTipVisibla(data.isNew)
			self:setIcon(data:getIcon())
			self:setIconKuang(data:getIconBg())
            self:setNumBgVisible( false )
--		    self:setLevel(data:getLevel())
			self:setEquiped( data.state == Enums.JewelState.inSlot )
            self:setLevelEx(data:getLevelPlus1())
        elseif type == Enums.ItemBagType.fame then
			self:setNewTipVisibla(false)
			self:setIcon(data:getIcon())
			self:setIconKuang(data:getIconBg())
			self:setNum(data:getAmount())
        elseif type == Enums.ItemBagType.mountSoul then
			self:setNewTipVisibla(false)
			self:setIcon(data:getIcon())
			self:setIconKuang(data:getIconBg())
			self:setNum(data:getAmount())
		elseif type == Enums.ItemBagType.partnerSoul then
			self:setNewTipVisibla(false)
			self:setIcon(data:getIcon())
			self:setIconKuang(data:getIconBg())
			self:setNum(data:getAmount())
		elseif type == Enums.ItemBagType.mapBuff then
			self:setNewTipVisibla(false)
			self:setIcon(data:getIcon())
			self:setIconKuang(data:getIconBg())
			self:setNum(data:getAmount())
		else
            -- print("IconRender1")
			self:setNewTipVisibla(false)
            if data then
			    self:setIcon(data.getIcon and data:getIcon())
    			self:setNum(data.getAmount and data:getAmount() or 0)
			    self:setIconKuang(data.getIconBg and data:getIconBg() or Res.Qulity_Icon_Bg[1])
            else
			    self:setNum(0)
			    self:setIconKuang(Res.Qulity_Icon_Bg[1])
            end
            -- print("IconRender2")
		end
	else	-- 没有数据，只显示一个外框
        self:setEmptyIcon(7)
        self:setLevelVisible(false)
        self:setPanelNumVisible(false)
	end
	self:refreshUIState()
end

function ClassRef:setLevelVisible(isVisible)
    self._ui.level:setVisible(isVisible)
end

function ClassRef:setPanelNumVisible(isVisible)
    self._ui.Panel_num:setVisible(isVisible)
end

-- 符文才有，符文类型icon
function ClassRef:setIconType(res)
	-- self._ui.icon_type:setVisible(res ~= nil)
	-- if res then
	-- 	self._ui.icon_type:loadTexture(res)
	-- end
end

function ClassRef:setEmptyIcon(idx)
    local index = idx or 2
    self:setIconKuang(Res.Qulity_Icon_Bg[index])
    self._ui.icon:setVisible(false)
end

function ClassRef:setIconKuang(res)
	self._ui.grade:loadTexture(res)
end

function ClassRef:setIcon(res)
    self._ui.icon:setVisible(true)
	self._ui.icon:loadTexture(res)
end

function ClassRef:setMaskVisible(b)
	self._ui.mask:setVisible(b)
	self:setUIMaskState(b)
end

function ClassRef:setRecommendVisible(b)
	local node = self._ui.Text_recommend
	if node then
		node:setVisible(b)
		self:setUIRecommendState(b)
	end
end

function ClassRef:setNumBgVisible(b)
	self._ui.Panel_num:setVisible(b)
end

function ClassRef:setLevel(level)
	if level and level > 0 then
    	self._ui.level:setVisible(true)
		self._ui.level:setString("+"..tostring(level))
	else
		self._ui.level:setVisible(false)
	end
end

function ClassRef:setLevelEx(level)
    if level and level > 0 then
        self._ui.level:setVisible(true)
        self._ui.level:setString(tostring(level)) -- 去掉了+号
    else
        self._ui.level:setVisible(false)
    end
end

function ClassRef:setNum(num)
	if not num then
		self:setNumBgVisible(false)
		return
	end
	local str = num >= self._defaultShowNumLimit and tostring(num) or ""
	self:setNumBgVisible(num >= self._defaultShowNumLimit)
	self._ui.num:setString(tostring(num))
end

function ClassRef:setDefaultShowNumLimit(num)
	self._defaultShowNumLimit = num
end

function ClassRef:setHasAmount(hasNum, onlyShowNeed)
    if not self._data then return end

    onlyShowNeed = onlyShowNeed or false
    local needNum = self._data:getAmount() or 1
    self:setNumBgVisible(true)
    self._ui.num:setString(onlyShowNeed and needNum or hasNum .. "/" .. needNum)
    self._ui.num:setTextColor(hasNum >= needNum and display.COLOR_WHITE or display.COLOR_RED)
end

function ClassRef:setNumberColor(color)
	self._ui.num:setTextColor(color)
end

function ClassRef:setNumString(ns)
    self:setNumBgVisible(true)
	self._ui.num:setString(ns)
end

function ClassRef:updateNumberSize()
	local pWidth = self._panel:getContentSize2() - 5
	local numWidth = self._ui.num:getContentSize2()
	if not self._numOScale then
		self._numOScale =  self._ui.num:getScale()
	end

	local scaleWidth = numWidth * self._numOScale
	if scaleWidth > pWidth then
		local scale = (scaleWidth - pWidth) / scaleWidth
		self._ui.num:setScale((self._numOScale - scale))
	else
		self._ui.num:setScale(self._numOScale)
	end
end

function ClassRef:setNewTipVisibla(b)
	-- self._ui.Icon_tips:setVisible(b)
	-- if b then
	-- 	display.playTimeline(self._ui.Icon_tips, nil, true)
	-- else
	-- 	display.pauseTimeline(self._ui.Icon_tips)
	-- end
end

function ClassRef:setChooseToCompose(b)
	self._ui.img_fill:setVisible(b)
	self:setUIChooseToCompose(b)
end

function ClassRef:setEquiped(b)
	self._ui.equipped:setVisible(b)
end

function ClassRef:isSelected()
	return self._ui.selected:isVisible()
end

function ClassRef:setSelected(b)
	self._ui.selected:setVisible(b)
	self:setUISelectedState(b)
end



function ClassRef:setClickEnable(b)
	self._panel:setTouchEnabled(b)
end

--pos = {x=, y=}
function ClassRef:setTipEnable(b, pos, isTouch)
	self._tipEnable = b
	self._tipPos = pos
	self._isTouchTip = isTouch or false
	self:addTouchEvent()
end

function ClassRef:setComparedTipEnabled(boEnabled)
    if self._tipEnable then
        self._comparedTipEnable = boEnabled
    end
end

-- tips 不显示来源，默认都显示
function ClassRef:setTipUnShowOrigin(b)
	self._unShowOrigin = b
end

function ClassRef:addTouchEvent()
	if self._isTouchTip then
		local function touchEvent(sender, eventType)
			if not self._isTouchTip then return end
			if eventType == ccui.TouchEventType.began then
				self._delayAct = sender:performWithDelay(function()
						self._delayAct = nil

						local worldPos = self._panel:convertToWorldSpace(cc.p(0,0))
						self._tipPos = self._tipPos or {x=2/5, y=1/2}
						if worldPos.x < display.cx then
							self._tipPos.x = 5/8
						else
							self._tipPos.x = 1/4
						end
						self:showTip()
					end, 0.1)

				self:setSelected(true)
			elseif eventType == ccui.TouchEventType.canceled or eventType == ccui.TouchEventType.ended then
				if self._delayAct then
					sender:stopAction(self._delayAct)
					self._delayAct = nil
					if eventType == ccui.TouchEventType.ended then
						executeFunc(self._onClick, self)
						self:dispatchCellEvent("click", self)
					end
				else
					UIHandler:hideFloatPanel()
				end
				self:setSelected(false)
			end
		end
		self._panel:addTouchEventListener(touchEvent)
	end
end

function ClassRef:showTip(pos)
	if self._tipEnable and self._data then
		local type = self._data.itemBagType
		local data = self._data

		local param = { itemId=tonumber(data.tid) }
		local tipsType
		if type == Enums.ItemBagType.daibi then
			tipsType = Enums.TipsType.daibi
		elseif type == Enums.ItemBagType.mount then
			tipsType = Enums.TipsType.mount
		elseif type == Enums.ItemBagType.equip then
			tipsType = Enums.TipsType.equip
		elseif type == Enums.ItemBagType.jewel then
			tipsType = Enums.TipsType.jewel
		elseif type == Enums.ItemBagType.fame then -- 声望的tips当代币处理
			param.itemId = tonumber(data.uid)
			tipsType = Enums.TipsType.fame
		elseif type == Enums.ItemBagType.mountSoul then
			param.itemId = tonumber(data.id)
			tipsType = Enums.TipsType.mountSoul
		elseif type == Enums.ItemBagType.partnerSoul then
			param.itemId = tonumber(data.id)
			tipsType = Enums.TipsType.partnerSoul
		elseif type == Enums.ItemBagType.partner then
			param.itemId = tonumber(data.id)
			tipsType = Enums.TipsType.partner
		elseif type == Enums.ItemBagType.fashion then
			tipsType = Enums.TipsType.fashion
		elseif type == Enums.ItemBagType.mapBuff then -- mapbuff 的tips未实现
			tipsType = Enums.TipsType.mapBuff
		else
			tipsType = Enums.TipsType.item
		end
        -- item
		param.dataTemp = data
        -- data类型
		param.tipsType = tipsType
        -- 是否不显示来源
		param.unShowOrigin = self._unShowOrigin
--		param.closeCallBack = function()
--			-- print("IconRender.removeTip")
--			if not tolua.isnull( self ) then
--				self:setSelected(false)
--			end
--		end
		param.contents = self._extraTipsContent
        -- callback
        local closeCallBack = function(tp)
            if not tolua.isnull(self) then
				self:clearTips()
				EM:notify(ViewEvent.Common_TipsClose)
				if self._tipsCloseCalllback then
					self._tipsCloseCalllback(tp)
				end
			end
        end
        param.closeCallBack = closeCallBack

		local boundingBoxTemp = self:getBoundingBox()
		local worldPosTemp = self:getParent():convertToWorldSpace( cc.p( boundingBoxTemp.x, boundingBoxTemp.y ) )
		boundingBoxTemp.x = worldPosTemp.x
		boundingBoxTemp.y = worldPosTemp.y

--		param.boundingBox = boundingBoxTemp
--		app:dispatchCustomEvent("EVENT_OPEN_FLOAT", {params=param})

        if cc.isDead(self._rightTip) then
            self._rightTip = newFloatTipsView.new(param)
            UIHandler:addPopupUi(self._rightTip, "m_floatView_Right", true)
            display.adjustNodePos(boundingBoxTemp, self._rightTip.mUINode, 10)
        else
            self._rightTip:refreshContent(param)
            display.adjustNodePos(boundingBoxTemp, self._rightTip.mUINode, 10)
        end
        self._rightTip:setVisible(true)

        -- 左侧对比tips，当前仅对比装备
        if self._comparedTipEnable then
            self:showComparedTip(boundingBoxTemp, closeCallBack)
            self:adjustPosition()
        end
	end
end

function ClassRef:_getEquipTipParams(equip)
    local params = {
        tipsType = Enums.TipsType.equip,
        itemId = equip.tid,
        uid = equip.uid,
        dataTemp = equip,
        equipGrids = UD:getEquipGrids(),
        equips = UD.equips,
        class = UD:getClass(),
        level = UD:getLevel(),
        specialistId = UD:getCurSpecTypeId(),
        unShowOrigin = true,
        shownOPbtn = true,      -- 设为true，才表示不显示
    }
    return params
end

function ClassRef:showComparedTip(boundingBoxTemp, closeCallBack)
    if not self._data then return end
    if self._data.itemBagType ~= Enums.ItemBagType.equip then return end

    local leftParams
    local item = self._data
    local wearEquip = UD:getEquipByPos(item:getPos())
    if wearEquip then
        leftParams = self:_getEquipTipParams(wearEquip)
    end

    if not leftParams then
        return
    end

    leftParams.closeCallBack = closeCallBack

    if not self._leftTip then
        self._leftTip = newFloatTipsView.new(leftParams)
        UIHandler:addPopupUi(self._leftTip, "m_floatView_left", true)
        display.adjustNodePos(boundingBoxTemp, self._leftTip.mUINode, 10)
    else
        self._leftTip:refreshContent(leftParams)
        display.adjustNodePos(boundingBoxTemp, self._leftTip.mUINode, 10)
    end
    self._leftTip:setVisible(true)
end

function ClassRef:adjustPosition()
    if self._leftTip and self._leftTip:isVisible() then -- 出现比较的情况
        local leftTipPosX = self._leftTip.mUINode:getPositionX()
        local leftTipSize = self._leftTip.mUINode:getContentSize()
        local leftTipHeight = leftTipSize.height

        local rightTipsPosX = self._rightTip.mUINode:getPositionX()
        local rightTipsPosY = self._rightTip.mUINode:getPositionY()
        local rightTipsSize = self._rightTip.mUINode:getContentSize()
        local rightTipsWidth = rightTipsSize.width
        local rightTipsHeight = rightTipsSize.height

        local leftPosX = leftTipPosX - rightTipsWidth
        local offsetX = 0
        if 10 > leftPosX then -- 左越界？
            offsetX = 10 - leftPosX
            leftPosX = 10
        end
        self._leftTip.mUINode:setPositionX(leftPosX)
        if rightTipsHeight > leftTipHeight then
            self._leftTip.mUINode:setPositionY(self._rightTip.mUINode:getPositionY() + rightTipsHeight - leftTipHeight)
        end
        self._rightTip.mUINode:setPositionX(rightTipsPosX + offsetX)
    end
end

function ClassRef:clearTips()
    if tolua.isnull(self) then
        return
    end

    if self._rightTip and self._rightTip:isVisible() then
        self._rightTip:setVisible(false)
    end

    if self._leftTip and self._leftTip:isVisible() then
        self._leftTip:setVisible(false)
    end

    self:setSelected(false)
end

-- 为了兼容，两个方法一样的效果
function ClassRef:setClickHandler(cb)
	self._onClick = cb
end
function ClassRef:onClick(cb)
	self._onClick = cb
end

function ClassRef:setTipsCloseCallBack(f)
	self._tipsCloseCalllback = f
end

function ClassRef:setStar(starNum)
	local panel = self._panel:getChildByName("Panel_star")
	if panel then
		panel:setVisible(true)
		for i =1, 5 do
			local starNode = panel:getChildByName("s"..i)
			if starNode then
				if i <= starNum then
					starNode:setVisible(true)
				else
					starNode:setVisible(false)
				end
			end
		end
	end
end

function ClassRef:hideStar()
	local panel = self._panel:getChildByName("Panel_star")
	if panel then
		panel:setVisible(false)
	end
end



------- listview 专用  兼容
--- listview 数据
function ClassRef:setCellModel(cellModel)
	self._cellModel = cellModel
end

function ClassRef:getCellModel()
	return self._cellModel
end

--在 listview 里面保存 UI状态
function ClassRef:setUISelectedState(b)
	if self._cellModel then
		self._cellModel:setUIState("selected", b)
	end
end

function ClassRef:setUIMaskState(b)
	if self._cellModel then
		self._cellModel:setUIState("mask", b)
	end
end

function ClassRef:setUIChooseToCompose(b)
	if self._cellModel then
		self._cellModel:setUIState("chooseToCompose", b)
	end
end

function ClassRef:setUIRecommendState(b)
	if self._cellModel then
		self._cellModel:setUIState("recommend", b)
	end
end


-- 在 listview 分发点击事件
function ClassRef:dispatchCellEvent(eventName, params)
	if self._cellModel then
		self._cellModel:dispatchEvent(eventName, params)
	end
end

function ClassRef:refreshUIState()
	if self._cellModel then
		self:setSelected(self._cellModel:getUIState("selected") == true)
		self:setMaskVisible(self._cellModel:getUIState("mask") == true)
		self:setChooseToCompose(self._cellModel:getUIState("chooseToCompose") == true)
		self:setRecommendVisible(self._cellModel:getUIState("recommend") == true)
	end
end

-- 设置额外的文本描述内容
function ClassRef:setExtraTipsContents(info)
	self._extraTipsContent = info
end



return ClassRef
